package com.cn.shuangzi.ad.activity;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.ISplashClickEyeListener;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.activity.SZSplashActivity;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.R;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.bean.AdShowTypeInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.tt.SplashClickEyeManager;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.util.SZArithUtil;
import com.cn.shuangzi.util.SZDateUtil;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;

import java.lang.ref.SoftReference;
import java.util.Date;
import java.util.List;


/**
 * Created by CN on 2017-11-28.
 */

public abstract class ADSplashActivity extends SZSplashActivity implements ADManager.OnSplashADLoadListener {
    private long remainTime;
    private Handler handlerAdShow;
    private TTAdNative mTTAdNative;
    private int SPLASH_SHOW_TIME_NORMAL = 1500;
    private int AD_SHOW_TIME = 5000;
    private final int FETCH_DELAY = ADConst.TIME_OUT;
    private long beginTime;
    private List<ADPlatform> adPlatformList;

    private String adType;
    private SZXmlUtil xmlUtil;
    private final String AD_SPLASH = "ad_splash";
    private final String AD_INTERVAL_TIMES = "ad_interval_times";
    private boolean isShowSkipBtnThisTime = true;
    private int adIntervalTimes = 2;
    private View.OnClickListener onVipSkipClickListener;
    private ADPlatform currentAdPlatform;
    private boolean isShowCutDown;
    private boolean isFromTTSplashClickEye;
    private Handler handlerCloseSplash;
    private AdShowTypeInfo adShowTypeInfoSplash;

    @Override
    public void onPreCreated() {
        xmlUtil = new SZXmlUtil(this, AD_SPLASH);
        onPreInitAd();
        SplashClickEyeManager.getInstance().setClickEyeShown(false);
        SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
        SplashClickEyeManager.getInstance().setClickEyeViewPos(isShowClickEyeLeft() ? SplashClickEyeManager.LEFT : SplashClickEyeManager.RIGHT);
        initCutDown();
        isDealToNext = false;
        isShowCutDown = false;
        if (isCanSkipAlways()) {
            isShowSkipBtnThisTime = true;
        } else {
            long time = xmlUtil.getLong(AD_SPLASH);
            if (time == 0) {
                isShowSkipBtnThisTime = false;
            } else {
                boolean isTodayShown = SZDateUtil.isSameDay(new Date(time), new Date());
                isShowSkipBtnThisTime = isTodayShown;
                if (adIntervalTimes > 0) {
                    if (isTodayShown) {
                        int times = xmlUtil.getInt(AD_INTERVAL_TIMES);
                        if (times > adIntervalTimes) {
                            isShowSkipBtnThisTime = false;
                            xmlUtil.put(AD_INTERVAL_TIMES, 1);
                        } else {
                            xmlUtil.put(AD_INTERVAL_TIMES, (++times));
                        }
                    } else {
                        xmlUtil.put(AD_INTERVAL_TIMES, 1);
                    }
                }
            }
        }
    }

    private AdShowTypeInfo getAdShowTypeInfoSplash() {
        if (adShowTypeInfoSplash == null) {
            adShowTypeInfoSplash = ADManager.getInstance().getSplashClickEyeAdShowType();
        }
        return adShowTypeInfoSplash;
    }

    public void autoCloseSplash() {
        //未知情况出现卡死的情况下，主动执行跳转
        handlerCloseSplash = new Handler();
        handlerCloseSplash.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (txtSkip != null && txtSkip.getVisibility() != View.VISIBLE) {
                    if (!isFinishing()) {
                        toMain();
                    }
                }
            }
        }, getSplashCloseDelayTimeInNoAd());
    }

    private void initCutDown() {
        txtSkip.setVisibility(View.GONE);
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanSkipAd()) {
//                    if(isToMain) {
//                        if (SplashClickEyeManager.getInstance().isSupportSplashClickEye()) {
//                            SplashClickEyeManager.getInstance().getSplashAd().startClickEye();
//                        }
//                    }
                    toMainByDelay(true);
//                    toMain();
                }
            }
        });
    }

    public void fetchSelfAD() {
        fetchSelfAD(null);
    }

    public void fetchSelfAD(ADManager.OnSplashADLoadListener onSplashADLoadListener) {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), onSplashADLoadListener);
    }

    public void fetchSelfADToHome() {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), this);
    }

    public void fetchSplashAD() {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSplash(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), this);
    }

    public void fetchTTSplashAD() {
        try {
            isShowCutDown = false;
            int height = 0;
            int width = 0;
            try {
                width = SZUtil.getScreenWidth(this);
                if (isFullScreenMode()) {
                    try {
                        height = SZUtil.getScreenHeight(this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    height = splash_container.getHeight();
                }
            } catch (Exception e) {
            }
            SZUtil.log("===============拉取穿山甲=================");
            mTTAdNative = TTAdManagerHolder.getInstance().createAdNative(this);
            //开屏广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(SZUtil.getTT_SPLASH_ID(this))
                    .setSupportDeepLink(true)
//                    .setSplashButtonType(TTAdConstant.SPLASH_BUTTON_TYPE_DOWNLOAD_BAR)
//                    .setDownloadType(TTAdConstant.DOWNLOAD_TYPE_POPUP)
                    .setImageAcceptedSize(width <= 0 ? 1080 : width, height <= 0 ? 1920 : height)
                    .build();
            //调用开屏广告异步请求接口
            mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
                @Override
                public void onError(int code, String message) {
                    SZUtil.log("穿山甲onError:" + message);
                    SZManager.getInstance().onUMEvent(ADConst.AD_THIRD_PLATFORM_ERROR_EVENT_ID,
                            ADManager.getInstance().getErrorEventMap(ADConst.AD_PLATFORM_TT,
                                    String.valueOf(code), message));
                    fetchNextPlatformAd();
                }

                @Override
                public void onTimeout() {
                    fetchNextPlatformAd();
                }

                @Override
                public void onSplashAdLoad(TTSplashAd ad) {
                    SZUtil.log("=======穿山甲成功======:" + ad);
                    if (ad == null) {
                        fetchNextPlatformAd();
                        return;
                    }

                    rltBottom.setVisibility(isFullScreenMode() ? View.GONE : View.VISIBLE);
                    //获取SplashView
                    View view = ad.getSplashView();

                    //初始化开屏点睛相关数据
                    initSplashClickEyeData(ad, view);

                    splash_container.removeAllViews();
                    //把SplashView 添加到ViewGroup中
                    splash_container.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮
                    //                if(!isCanSkipAd()) {
                    ad.setNotAllowSdkCountdown();
                    //                }
                    //设置SplashView的交互监听器
                    ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                        @Override
                        public void onAdClicked(View view, int type) {
                            SZUtil.log("=====头条广告点击=====");
                        }

                        @Override
                        public void onAdShow(View view, int type) {
                            SZUtil.log("=====头条广告展示=====");
                            if (adType == null) {
                                adType = ADConst.AD_PLATFORM_TT;
                                ADManager.getInstance().setAdShownCompany(ADConst.AD_PLATFORM_TT);
                                SZManager.getInstance().onUMEvent(ADConst.AD_SPLASH_EXPOSURE_EVENT_ID, ADConst.AD_PLATFORM_TT);
                                showCutDown();
                            }
                        }

                        @Override
                        public void onAdSkip() {
                            SZUtil.log("=======穿山甲onAdSkip======");
                            toNext();
                        }

                        @Override
                        public void onAdTimeOver() {
                            SZUtil.log("=======穿山甲onAdTimeOver======");

                            if (!isShowAdTime()) {
                                toNext();
                            }
                        }
                    });
                }
            }, FETCH_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
            toNext();
        }
    }

    private SplashClickEyeListener mSplashClickEyeListener;

    private void initSplashClickEyeData(TTSplashAd splashAd, View splashView) {
        SplashClickEyeManager.getInstance().setSupportSplashClickEye(true);
        if (splashAd == null || splashView == null) {
            return;
        }
        isFromTTSplashClickEye = true;
        mSplashClickEyeListener = new SplashClickEyeListener(this, splashAd, splash_container);

        splashAd.setSplashClickEyeListener(mSplashClickEyeListener);
        SplashClickEyeManager.getInstance().setSplashInfo(splashAd, splashView, getWindow().getDecorView());
    }

    public class SplashClickEyeListener implements ISplashClickEyeListener {
        private SoftReference<Activity> mActivity;
        private TTSplashAd mSplashAd;
        private View mSplashContainer;

        public SplashClickEyeListener(Activity activity, TTSplashAd splashAd, View splashContainer) {
            mActivity = new SoftReference<>(activity);
            mSplashAd = splashAd;
            mSplashContainer = splashContainer;
            SZUtil.log("=========初始化穿山甲点睛监听事件=========");
        }

        @Override
        public void onSplashClickEyeAnimationStart() {
            SZUtil.log("=========点睛动画开始onSplashClickEyeAnimationStart=========");
            //开始执行开屏点睛动画
            if (isFromTTSplashClickEye) {
                startSplashAnimationStart();
            }
        }

        @Override
        public void onSplashClickEyeAnimationFinish() {
            //sdk关闭了了点睛悬浮窗
            boolean isSupport = SplashClickEyeManager.getInstance().isSupportSplashClickEye();
            SZUtil.log("sdk关闭了点睛悬浮窗：" + isSupport);
            if (isFromTTSplashClickEye && isSupport) {
                toMainByDelay(true);
            }
            SplashClickEyeManager.getInstance().clearSplashStaticData();
        }

        @Override
        public boolean isSupportSplashClickEye(boolean isSupport) {
            if (getAdShowTypeInfoSplash() != null) {
                switch (getAdShowTypeInfoSplash().getClickEyeMode()) {
                    case AdShowTypeInfo.ALWAYS_MODE:
                        SplashClickEyeManager.getInstance().setSupportSplashClickEye(true);
                        break;
                    case AdShowTypeInfo.LAUNCH_MODE:
                        SplashClickEyeManager.getInstance().setSupportSplashClickEye(isToMain);
                        break;
                    case AdShowTypeInfo.NORMAL_MODE:
                        SplashClickEyeManager.getInstance().setSupportSplashClickEye(isSupport);
                        break;
                    case AdShowTypeInfo.CLOSE_MODE:
                        SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
                        break;
                    default:
                        SplashClickEyeManager.getInstance().setSupportSplashClickEye(isSupport);
                        break;
                }
            } else {
                SplashClickEyeManager.getInstance().setSupportSplashClickEye(isSupport);
            }
            SZUtil.log("物料是否支持点睛：" + isSupport);
            return false;
        }

        private void startSplashAnimationStart() {
            if (mActivity.get() == null || mSplashAd == null || mSplashContainer == null) {
                return;
            }
            ViewGroup content = mActivity.get().findViewById(android.R.id.content);
            SplashClickEyeManager.getInstance().startSplashClickEyeAnimation(mSplashContainer, content, content, new SplashClickEyeManager.AnimationCallBack() {
                @Override
                public void animationStart(int animationTime) {
                }

                @Override
                public void animationEnd() {
                    if (mSplashAd != null) {
                        mSplashAd.splashClickEyeAnimationFinish();
                    }
                }
            });
        }
    }

    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     */
    public void fetchGDTSplashAD() {
        try {
            isShowCutDown = false;
            SZUtil.log("==========拉取广点通=========");
            String posId = SZUtil.getGDT_SPLASH_ID(this);
            new SplashAD(this, posId, new SplashADListener() {
                @Override
                public void onADDismissed() {
                    toNext();
                }

                @Override
                public void onNoAD(AdError adError) {
                    SZUtil.log("广点通Error|Code:" + adError.getErrorCode() + "|Msg:" + adError.getErrorMsg());
                    SZManager.getInstance().onUMEvent(ADConst.AD_THIRD_PLATFORM_ERROR_EVENT_ID,
                            ADManager.getInstance().getErrorEventMap(ADConst.AD_PLATFORM_GDT,
                                    String.valueOf(adError.getErrorCode()), adError.getErrorMsg()));
                    fetchNextPlatformAd();
                }

                @Override
                public void onADPresent() {
                    if (adType == null) {
                        adType = ADConst.AD_PLATFORM_GDT;
                        ADManager.getInstance().setAdShownCompany(ADConst.AD_PLATFORM_GDT);
                    }
                }

                @Override
                public void onADClicked() {
                }

                @Override
                public void onADTick(long l) {
                    if (!isShowCutDown) {
                        SZUtil.log("广点通开屏剩余时间：" + l);
                        AD_SHOW_TIME = (int) (Math.ceil(SZArithUtil.div(l, 1000)) * 1000);
                        showCutDown();
                    }
                }

                @Override
                public void onADExposure() {

                    if (!isShowAdTime()) {
                        toNext();
                    }
                    SZManager.getInstance().onUMEvent(ADConst.AD_SPLASH_EXPOSURE_EVENT_ID, ADConst.AD_PLATFORM_GDT);
                    SZUtil.log("=====广点通广告展示=====");
                }

                @Override
                public void onADLoaded(long l) {
                    SZUtil.log("广点通广告onADLoaded:" + l);

                }
            }, 0).fetchAndShowIn((ViewGroup) findViewById(R.id.splash_container));
        } catch (Exception e) {
            e.printStackTrace();
            toNext();
        }
    }

    @Override
    public void toMain() {
        if(isCloseAllClickEye()){
            if (SplashClickEyeManager.getInstance().isSupportSplashClickEye()) {
                if (SplashClickEyeManager.getInstance().getSplashAd() == null) {
                    SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
                } else {
                    SplashClickEyeManager.getInstance().getSplashAd().startClickEye();
                }
            }else {
                SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
            }
        }else {
            if (isToMain && !isShowClickEyeInLaunch()) {
                SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
                super.toMain();
                return;
            }
            if (SplashClickEyeManager.getInstance().isSupportSplashClickEye()) {
                if (SplashClickEyeManager.getInstance().getSplashAd() == null) {
                    SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
                } else {
                    SplashClickEyeManager.getInstance().getSplashAd().startClickEye();
                }
            }
        }
        super.toMain();
    }

    private boolean isDealToNext = false;

    private void toNext() {
        if (!isDealToNext) {
            next();
        }
        isDealToNext = true;
    }

    private boolean isShowAdTime() {
        if (currentAdPlatform == null || currentAdPlatform.getAdShowTypeInfo() == null || currentAdPlatform.getAdShowTypeInfo().getLastSecond() <= 0) {
            return false;
        }
        return true;
    }

    private void showCutDown() {
        isShowCutDown = true;
        if (isShowVipSkipBtn()) {
            txtVipSkip.setVisibility(View.VISIBLE);
            if (onVipSkipClickListener == null) {
                txtVipSkip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            startActivity(getVipActivity());
                        } catch (Exception e) {
                        }
                    }
                });
            } else {
                txtVipSkip.setOnClickListener(onVipSkipClickListener);
            }
        } else {
            txtVipSkip.setVisibility(View.GONE);
        }
        if (handlerAdShow != null) {
            handlerAdShow.removeCallbacksAndMessages(null);
        }
        txtSkip.setVisibility(View.VISIBLE);
        if (handlerAdShow == null) {
            handlerAdShow = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case 200:
                            if (isShowAdTime()) {
                                remainTime -= 1000;
                                if (remainTime <= 0) {
                                    remainTime = 0;
                                }
                                txtSkip.setText(getSkipText());
                                if (remainTime == 0) {
                                    toNext();
                                } else {
                                    handlerAdShow.sendEmptyMessageDelayed(200, 1000);
                                }
                            }
                            break;
                    }
                }
            };
        }
        long timeShow = getAdShowTimeUserDefine() <= 0 ? AD_SHOW_TIME : getAdShowTimeUserDefine();
        remainTime = isCanSkipAd() ? timeShow : AD_SHOW_TIME;
        txtSkip.setText(getSkipText());
        handlerAdShow.sendEmptyMessageDelayed(200, 1000);
        xmlUtil.put(AD_SPLASH, System.currentTimeMillis());
    }

    private boolean isCanSkipAd() {
        if (isCanSkipAlways()) {
            return true;
        }
        return isShowSkipBtnThisTime;
    }

    private String getSkipText() {
        if (isCanSkipAd() && !isShowAdTime()) {
            return getString(R.string.txt_skip);
        }
        return isCanSkipAd() ? (getString(R.string.txt_skip) + " " + remainTime / 1000) : String.valueOf(remainTime / 1000);
    }

    private void toMainByDelay(boolean isNowSkip) {

        if (isFromTTSplashClickEye) {
            if (SplashClickEyeManager.getInstance().isSupportSplashClickEye()) {
//                return;
            } else {
                SZUtil.log("物料不支持点睛");
                SplashClickEyeManager.getInstance().clearSplashStaticData();
            }
        }
        if (isNowSkip) {
            toMain();
        } else {
            long delay = getDelayFinishTime();
            toMain(delay);
        }
    }

    private long getDelayFinishTime() {
        long errorTime = System.currentTimeMillis();
        long remainderTime = SPLASH_SHOW_TIME_NORMAL - (errorTime - beginTime);
        return remainderTime > 0 ? remainderTime : 0;
    }

    @Override
    public void onFetchAdSuccess(List<ADPlatform> adPlatformList) {
        SZUtil.log("adPlatformList:" + adPlatformList);
        this.adPlatformList = adPlatformList;
        if (adPlatformList != null && adPlatformList.size() > 0) {
            try {
                ADPlatform adPlatform = adPlatformList.get(ADConst.LOAD_AD_INDEX);
                if (adPlatform.isAdIsOpen()) {
                    fetchPlatformAd(adPlatform);
                } else {
                    toMainByDelay(false);
                }
            } catch (Exception e) {
                e.printStackTrace();
                toMainByDelay(false);
            }
        } else {
            toMainByDelay(false);
        }
    }

    private void fetchNextPlatformAd() {
        if (adPlatformList != null && adPlatformList.size() > 0) {
            fetchPlatformAd(adPlatformList.get(0));
        } else {
            toMainByDelay(false);
        }
    }

    private void fetchSelfSplashAD(ADPlatform adPlatform) {
        //todo 显示自营广告
    }

    private void fetchPlatformAd(ADPlatform adPlatform) {
        if (adPlatform != null) {
            ADManager.getInstance().initAd();
            this.currentAdPlatform = adPlatform;
            if (adPlatform.getAdShowTypeInfo() != null) {
                if (adPlatform.getAdShowTypeInfo().getLastSecond() > 0) {
                    AD_SHOW_TIME = adPlatform.getAdShowTypeInfo().getLastSecond();
                } else {
                    AD_SHOW_TIME = Integer.MAX_VALUE;
                }
            }
            adPlatformList.remove(adPlatform);
            switch (adPlatform.getAdSupportType()) {
                case ADConst.AD_PLATFORM_TT:
                    fetchTTSplashAD();
                    break;
                case ADConst.AD_PLATFORM_GDT:
                    fetchGDTSplashAD();
                    break;
                default:
                    toMainByDelay(false);
            }
        } else {
            toMainByDelay(false);
        }
    }

    public void init(boolean isShowAd) {
        init(isShowAd, 1000);
    }

    public void init(boolean isShowAd, long delayToMain) {
        SZApp.getInstance().init();
        dealAd(isShowAd, delayToMain);
    }

    public void dealAd(boolean isShowAd) {
        dealAd(isShowAd, 1000);
    }

    public void dealAd(boolean isShowAd, long delayToMain) {
        if (isShowAd) {
            autoCloseSplash();
            SZUtil.log("设置自动关闭成功");
            fetchSplashAD();
        } else {
            SZUtil.log("不展示广告，直接进主页");
            toMain(delayToMain);
        }
    }

    @Override
    public void onFetchAdError() {
        toMainByDelay(false);
    }

    public long getAdShowTimeUserDefine() {
        return 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyHandlerMessage();
    }

    private void destroyHandlerMessage() {
        try {
            if (handlerAdShow != null) {
                handlerAdShow.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (handlerCloseSplash != null) {
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerAdShow = null;
        handlerCloseSplash = null;
    }

    public long getSplashCloseDelayTimeInNoAd() {
        return FETCH_DELAY + 150;
    }

    @Override
    public boolean isShowTitleInit() {
        return false;
    }

    public void setSplashShowTime(int splash_show_time_normal) {
        this.SPLASH_SHOW_TIME_NORMAL = splash_show_time_normal;
    }

    public void setADShowTime(int ad_show_time) {
        this.AD_SHOW_TIME = ad_show_time;
    }

    public int getAdIntervalTimes() {
        return adIntervalTimes;
    }

    public void setAdIntervalTimes(int adIntervalTimes) {
        this.adIntervalTimes = adIntervalTimes;
    }

    public View.OnClickListener getOnVipSkipClickListener() {
        return onVipSkipClickListener;
    }

    public void setOnVipSkipClickListener(View.OnClickListener onVipSkipClickListener) {
        this.onVipSkipClickListener = onVipSkipClickListener;
    }

    public void onPreInitAd() {
    }

    public abstract void onCreated();

    public abstract int getSplashRes();

    public abstract int getAppIconRes();

    public abstract int getAppNameRes();

    public abstract int getAppNameColorRes();

    public abstract Class getHomeActivity();

    public abstract boolean isShowVipSkipBtn();

    public abstract Class<?> getVipActivity();

    public abstract boolean isFullScreenMode();

    public abstract boolean isShowClickEyeInLaunch();

    public abstract boolean isCloseAllClickEye();

    public abstract boolean isShowClickEyeLeft();

    public boolean isCanSkipAlways() {
        return true;
    }

}

